﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web;
using System.IO;
using System.Configuration;

namespace Company.StudyClub.BLL.Common
{
    public static class Utility
    {
        public readonly static string Source = ConfigurationManager.AppSettings["SourceDomain"];

        public static string TextEncoding(string text)
        {
            text = text.Replace(((char)92).ToString(), ((char)92).ToString() + ((char)92).ToString());
            text = text.Replace(((char)39).ToString(), ((char)92).ToString() + ((char)39).ToString());
            text = text.Replace(((char)34).ToString(), ((char)92).ToString() + ((char)34).ToString());
            text = text.Replace(((char)13).ToString(), ((char)92).ToString() + "n");
            text = text.Replace(((char)10).ToString(), "");
            return text;
        }

        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="inputStr">原字符串</param>
        /// <param name="length">英文长度</param>
        /// <param name="needAdd">是否添加"…"</param>
        /// <returns>截取后的字符串</returns>
        public static string SubString(string inputStr, int length, bool needAdd)
        {
            if (inputStr.Length * 2 <= length)
            {
                // 不论是英文还是中文，都比截取长度小
                // 则直接返回
                return inputStr;
            }

            StringBuilder sb = new StringBuilder();
            int tempLen = 0;
            // 最后一个字符是否为中文
            bool lastAdd = true;

            ASCIIEncoding ascii = new ASCIIEncoding();
            byte[] s = ascii.GetBytes(inputStr);

            for (int i = 0; i < s.Length; i++)
            {
                if ((int)s[i] == 63)
                {
                    // 中文，长度 + 2
                    tempLen += 2;
                    lastAdd = true;
                }
                else
                {
                    // 英文，长度 + 1
                    tempLen += 1;
                    lastAdd = false;
                }

                try
                {
                    // 加一个字
                    sb.Append(inputStr.Substring(i, 1));
                }
                catch
                {
                    break;
                }

                if (tempLen >= length)
                    break;
            }

            //如果截过则加上半个省略号
            byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputStr);
            if (mybyte.Length > length)
            {
                if (needAdd)
                {
                    if (sb.Length < 2)
                    {
                        sb.Remove(0, 1);
                        sb.Append("…");
                    }
                    else
                    {
                        if (lastAdd)
                        {
                            sb.Remove(sb.Length - 1, 1);
                            sb.Append("…");
                        }
                        else
                        {
                            sb.Remove(sb.Length - 2, 2);
                            sb.Append("…");
                        }
                    }
                }
            }

            return sb.ToString();
        }

        public static string RemoveHtml(string html)
        {
            return RemoveHtml(html, 0);
        }

        public static string RemoveScript(string html)
        {
            Regex regex1 = new Regex(@"<script[\s\S]+</script *>", RegexOptions.IgnoreCase);
            Regex regex9 = new System.Text.RegularExpressions.Regex(@"<[^>]*>", RegexOptions.IgnoreCase);
            html = regex1.Replace(html, ""); //过滤<script></script>标记
            html = regex9.Replace(html, "");//过滤html标记
            return html;
        }

        public static string RemoveHtml(string html, int charLimit)
        {
            if (html == null || html.Trim().Length == 0)
                return string.Empty;

            string nonhtml = Regex.Replace(html, "<[^>]+>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            if (charLimit <= 0 || charLimit >= nonhtml.Length)
                return nonhtml;

            int place = charLimit;
            int len = nonhtml.Length - 1;

            while (!Char.IsWhiteSpace(nonhtml[place]) && place < len)
                place++;

            return nonhtml.Substring(0, place) + "...";
        }

        public static string CheckParameter(string param)
        {
            if (param == null || param == string.Empty)
            {
                return string.Empty;
            }
            
            param = param.Replace("'", "''");

            return param;
        }

        public static string TimeSwitch(int seconds)
        {
            int hour = seconds / 3600;
            int minute = (seconds - hour * 3600) / 60;
            int second = (seconds - hour * 3600) % 60;

            if (seconds <= 0)
                return "--";

            string strRunTime = string.Empty;

            if (hour > 0)
                strRunTime += hour + "小时";
            if (minute > 0)
                strRunTime += minute + "分钟";
            if (second > 0)
                strRunTime += second + "秒";

            return strRunTime;
        }

        public static string GetCourseType(int courseType)
        {
            switch (courseType)
            {
                case 1: return "Scorm 1.2";
                case 2: return "非标准课程";
                default: return string.Empty;
            }
        }

        public static string FilePath(string filePath)
        {
            Control objControl = new Control();
            return objControl.ResolveClientUrl("~/" + filePath);
        }
        public static string GetCourseCoverIcon(string fileName)
        {
            if (fileName == string.Empty)
            {
                fileName = "default.gif";
            }
            return FilePath("data/coursepicture/" + fileName);
        }

        public static void SaveErrorLogFile(string message)
        {
            if (message == string.Empty)
                return;

            string strDirectory = HttpContext.Current.Server.MapPath("~/Data/Log/");

            if (!Directory.Exists(strDirectory))
            {
                Directory.CreateDirectory(strDirectory);
            }
            string strLogFilePath = strDirectory + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";

            StreamWriter swLog = File.AppendText(strLogFilePath);
            swLog.WriteLine(message);
            swLog.Close();
        }
    }
}
